using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace SampleI2CRTC
{
    class DS1307
    {
        I2CDevice ds1307;
        public byte year, month, day, wday, hour, min, sec;
        public int timeout;
        private byte[] cmd = new byte[2];
        private byte[] addr = new byte[1] { 0x00 };
        private byte[] data = new byte[7];
        private I2CDevice.I2CTransaction[] wr = new I2CDevice.I2CTransaction[1];
        private I2CDevice.I2CTransaction[] rd = new I2CDevice.I2CTransaction[2];

        private byte BcdToDec(byte bcd)
        {
            return (byte)((bcd >> 4) * 10 + (bcd & 0xf));
        }

        public void Cmd(byte address, byte data)
        {
            cmd[0] = address;
            cmd[1] = data;
            ds1307.Execute(wr, timeout);
        }

        public void start()
        {
            Cmd(0x00, 0x00); // Control 1 : 0x00
        }

        public void Stop()
        {
            Cmd(0x00, 0x80); // Control 1 : 0x80
        }

        public void Read()
        {
            ds1307.Execute(rd, timeout);
            sec =   BcdToDec((byte)(data[0] & 0x7f));
            min =   BcdToDec((byte)(data[1] & 0x7f));
            hour =  BcdToDec((byte)(data[2] & 0x3f));
            wday =  data[3];
            day =   BcdToDec((byte)(data[4] & 0x3f));
            month = BcdToDec((byte)(data[5] & 0x1f));
            year =  BcdToDec(data[6]);
        }

        public void Write()
        {
            Cmd(0x00, sec);
            Cmd(0x01, min);
            Cmd(0x02, hour);
            Cmd(0x03, wday);
            Cmd(0x04, day);
            Cmd(0x05, month);
            Cmd(0x06, year);
        }

        public void Dispose()
        {
            ds1307.Dispose();
        }

        public DS1307(int clockRate, int timeout)
        {
            this.timeout = timeout;

            // define transaction
            wr[0] = I2CDevice.CreateWriteTransaction(cmd);  // for sendcmd()
            rd[0] = I2CDevice.CreateWriteTransaction(addr); // for read()
            rd[1] = I2CDevice.CreateReadTransaction(data);  // for read()

            ds1307 = new I2CDevice(new I2CDevice.Configuration(0x68, clockRate));
        }
    }
}
